package com.dankegongyu.lib.common.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dankegongyu.lib.common.annotation.BindEventBus;
import com.dankegongyu.lib.common.event.DKEventBus;
import com.dankegongyu.lib.common.rx.presenter.IPresenter;
import com.dankegongyu.lib.common.util.fresco.FrescoImageHelper;
import com.trello.rxlifecycle3.components.support.RxFragment;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 懒加载 refs: http://blog.csdn.net/itluochen/article/details/52185125
 * 注意：如果是ViewPager中使用，需要设置mViewPager.setOffscreenPageLimit(fragments.size() - 1);
 *
 * @author WuPuquan
 * @version 1.0
 * @since 2017/9/14 11:23
 */

public abstract class CommonBaseLazyFragment extends RxFragment implements IBaseFragment {

    private Unbinder unbinder;

    private boolean isFirstVisible = true;
    private boolean isViewCreated = false;
    private boolean isLazyLoaded = false;

    protected List<IPresenter> mPresenterList = new ArrayList<>();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser && isFirstVisible) {
            isFirstVisible = false;
            initPrepare();
            return;
        }

        // Visible状态变化时可以执行某些操作，由于生命周期的原因，第一次调用setUserVisibleHint时不执行
        if (!isFirstVisible) {
            onUserVisibleStateChanged(isVisibleToUser);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        Logger.d("onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getContentViewLayoutId() != 0) {
            View rootView = inflater.inflate(getContentViewLayoutId(), container, false);
            unbinder = ButterKnife.bind(this, rootView);
            if (this.getClass().isAnnotationPresent(BindEventBus.class)) {
                DKEventBus.register(this);
            }
            return rootView;
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        init(savedInstanceState);

        isViewCreated = true;
        initPrepare();
    }

    private void initPrepare() {
        if (getUserVisibleHint() && isViewCreated && !isLazyLoaded) {
            // Presenter
            initPresenter();
            for (IPresenter p : mPresenterList) {
                if (p != null) {
                    p.onCreate();
                }
            }
            // 必须保证在onCreateView执行完以后，否则操作界面可能空指针
            doBusiness();
            isLazyLoaded = true;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        // 1.EventBus解注册
        if (this.getClass().isAnnotationPresent(BindEventBus.class)) {
            DKEventBus.unregister(this);
        }

        // 2.Presenter销毁
        for (IPresenter p : mPresenterList) {
            if (p != null) {
                p.onDestroy();
            }
        }

        // 3.ButterKnife取消绑定，必须在Presenter销毁之后，否则容易造成空指针
        if (unbinder != null) {
            unbinder.unbind();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        FrescoImageHelper.clearMemoryCaches();
    }

    protected void addPresenter(IPresenter presenter) {
        if (presenter != null) {
            mPresenterList.add(presenter);
        }
    }

    /**
     * Called when the fragment is visible first time
     */
//    protected abstract void onLazyLoadData();

    /**
     * Called when the user visible state has changed.
     *
     * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
     *                        false if it is not.
     */
    protected void onUserVisibleStateChanged(boolean isVisibleToUser) {

    }

    protected void finishActivity() {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }
}
